package com.zmn.brs.admin.controller.event;

import com.zmn.brs.business.interfaces.event.EventBService;
import com.zmn.brs.common.constant.RedisKeyConst;
import com.zmn.brs.common.enums.EventTypeEnum;
import com.zmn.brs.common.enums.SceneTypeEnum;
import com.zmn.brs.model.entity.event.Event;
import com.zmn.brs.model.entity.event.EventQuery;
import com.zmn.brs.model.entity.scene.Scene;
import com.zmn.brs.model.vo.event.ObjEventVO;
import com.zmn.brs.services.interfaces.event.EventService;
import com.zmn.brs.services.interfaces.scene.SceneService;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.plat.common.dictionary.StatusEnum;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 描述: 业务场景事件配置
 * @author chongw
 * @since 2021-05-28
 **/
@Controller
@RequestMapping(value = "/brs/event/")
public class EventModifyController extends EventBaseController {

    @Resource
    private EventService eventService;

    @Resource
    private SceneService sceneService;

    @Resource
    private EventBService eventBService;

    @Resource
    RedisTemplate<String, Integer> redisTemplate;

    /**
     * 描述: 添加事件
     * @param objEventVO 事件对象
     * @return com.zmn.common.dto.ResultDTO
     **/
    @ResponseBody
    @RequestMapping(value = "addEvent")
    public ResponseDTO addEvent(@RequestBody ObjEventVO objEventVO) {
        try {
            List<Integer> subgoalIdList = Optional.ofNullable(objEventVO.getSubgoalIdList()).orElse(new ArrayList<>());
            for(Integer subgoalId : subgoalIdList){
                EventQuery eventQuery = new EventQuery();
                eventQuery.setRelateId(subgoalId);
                eventQuery.setEventType(EventTypeEnum.OBJECTIVE.getTypeId());
                eventQuery.setStatus(StatusEnum.ENABLE.getCode());
                Integer count = eventService.countByQuery(eventQuery);
                if(count > 0){
                    return ResponseDTO.fail(String.format("ID【%s】目标事件已存在！", subgoalId));
                }
            }
            objEventVO.setMcStaffName(super.getMcStaffRealName());
            Integer falg = eventService.addEvent(objEventVO);
            if(falg > 0){
                return ResponseDTO.success(true,"添加事件成功！");
            }
            return ResponseDTO.fail("添加事件失败！");
        } catch (Exception e) {
            logger.error("添加事件异常，异常信息：" + e);
            return ResponseDTO.fail("添加事件异常！");
        }
    }

    /**
     * 描述: 修改事件
     * @param event 事件对象
     * @return com.zmn.common.dto.ResultDTO
     **/
    @ResponseBody
    @RequestMapping(value = "modifyEvent")
    public ResponseDTO modifyEvent(@RequestBody Event event) {
        try {
            if(event == null){
                return ResponseDTO.fail("参数不能为空！");
            }
            //Event event = JSONObject.parseObject(JSONObject.toJSONString(map) , Event.class);
            if(NumberUtil.isNullOrZero(event.getEventId())){
                return ResponseDTO.fail("事件ID不能为空！");
            }
            if(StringUtil.isBlank(event.getEventName())){
                return ResponseDTO.fail("事件名称不能为空！");
            }
            Event cevent = eventService.findById(event.getEventId());
            cevent.setEventName(event.getEventName());
            cevent.setRemarks(event.getRemarks());
            cevent.setCubeSnapshotId(event.getCubeSnapshotId());
            cevent.setUpdater(super.getMcStaffRealName());
            cevent.setUpdateTime(DateUtil.getNow());
            cevent.setTriggerTime(event.getTriggerTime());
            cevent.setCommon(event.getCommon());
            //获取事件场景
            Scene scene = sceneService.findById(cevent.getSceneId());
            //判断是否是绩效经营指标监控，是则检验以下数据必填
            if(scene != null && SceneTypeEnum.TARGET.getTypeId().equals(scene.getType())){
                if(NumberUtil.isNullOrZero(event.getCubeSnapshotId())){
                    return ResponseDTO.fail("快照ID不能为空！");
                }
            }
            Integer flag = eventService.updateEventByKey(cevent);
            if(flag > 0){
                //初始化事件类型
                eventBService.initEventTypeJob(cevent.getEventType());
                return ResponseDTO.success(true,"事件修改成功！");
            }
            return ResponseDTO.fail("事件修改失败！");
        } catch (Exception e) {
            logger.error("事件修改异常，异常信息：", e);
            return ResponseDTO.fail("事件修改异常！");
        }
    }

    /**
     * 启用场景
     * @param ids
     * @return
     */
    @ResponseBody
    @RequestMapping("enable")
    public ResponseDTO enable(@RequestParam(value = "ids") List<Integer> ids){
        if(ids.isEmpty()) return ResponseDTO.fail("请选择需要启用的数据！");
        //批量修改规则状态
        Integer flag = this.modifyStatus(ids, StatusEnum.ENABLE.getCode());
        if(flag > 0){
            return ResponseDTO.success(null,"启用成功！");
        }
        return ResponseDTO.fail("启用失败！");
    }

    /**
     * 停用事件
     * @param ids
     * @return
     */
    @ResponseBody
    @RequestMapping("disable")
    public ResponseDTO disable(@RequestParam(value = "ids") List<Integer> ids){
        if(ids.isEmpty()) return ResponseDTO.fail("请选择需要停用的数据！");
        //批量修改事件状态
        Integer flag = this.modifyStatus(ids,StatusEnum.DISABLE.getCode());
        if(flag > 0){
            return ResponseDTO.success(null,"停用成功！");
        }
        return ResponseDTO.fail("停用失败！");
    }

    /**
     * 修改事件状态
     * @param eventIdList
     * @param status
     * @return
     */
    private Integer modifyStatus(List<Integer> eventIdList,Integer status){
        //设置需要修改的属性值
        List<Event> eventList = eventIdList.stream().map(o->{
            Event event = new Event();
            event.setEventId(o);
            event.setStatus(status);
            event.setUpdater(super.getMcStaffRealName());
            event.setUpdateTime(DateUtil.getNow());
            return event;
        }).collect(Collectors.toList());
        Integer flag = eventService.updateBatchByKey(eventList);
        if(flag > 0){
            eventIdList.stream().forEach(o -> {
                String redisKey = RedisKeyConst.getStatusRedisKey(RedisKeyConst.EVENT_STATUS_REDIS_KEY, o);
                redisTemplate.opsForValue().set(redisKey, status);
                //初始化任务
                eventBService.initEventJob(o);
            });
        }
        return flag;
    }

}
